package com.t.bricks.bussiness.service.system.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import com.t.bricks.bussiness.model.HtmlFormControlInfo;
import com.t.bricks.bussiness.model.HtmlFormInfo;
import com.t.bricks.bussiness.service.system.HtmlDesignService;
import com.t.bricks.model.Log;
import com.t.bricks.model.MsgEmity;
import com.t.bricks.utils.function.file.FileUtil;
import com.t.bricks.utils.spring.ModuleUtil;

@Service
public class HtmlDesignServiceImpl implements HtmlDesignService {
	
	/**
	 * 保存页面
	 * @param htmlFormInfos
	 * @return
	 */
	@Override
	public MsgEmity save(HtmlFormInfo htmlFormInfos) {
		if (null == htmlFormInfos) {
			return MsgEmity.err(8001, "数据参数为空");
		}
		
		String[] entry = readHtml(htmlFormInfos);
				
		String html = entry[1];
		if (null == html || "".equals(html.trim())) {
			return MsgEmity.err(8002, "未找到文件");
		}
		
		Document doc = Jsoup.parse(html);

		List<HtmlFormControlInfo> sortlist = htmlFormInfos.getHtmlFormControlInfos();
		sortPoint(sortlist);//排序坐标
		
		StringBuilder ht = new StringBuilder();
		for (HtmlFormControlInfo control : sortlist) {
			Elements rows = doc.select("el-form el-row el-col[data-name='" + control.getsName() + "']");
			if (rows.size() < 1 || null == rows.get(0)) {
				continue;//没有找到
			}
			Element element = rows.get(0);
			element.attr(":span", String.valueOf(control.getiColSize()));
			
			ht.append(element.outerHtml());
		}
		
		doc.select("el-form el-row").html(ht.toString());
		doc.select("el-form").attr("data-min-height", String.valueOf(htmlFormInfos.getiFormHeight()));
		doc.select("el-form").attr("data-min-width", String.valueOf(htmlFormInfos.getiFormWidth()));
		
		html = doc.select("body").get(0).html();
		if (!FileUtil.saveStr(entry[0], html)) {
			return MsgEmity.err(8003, "保存设计失败");
		}
		
		String sUserId = ModuleUtil.currentLoginUserId();
		if ("/00000000/00000001".contains(sUserId)) {
			String temp = entry[0].replaceAll(
					new StringBuilder().append("_").append(sUserId).append(".html").toString(),
					"_default.html");
			FileUtil.saveStr(temp, html);//保存默认页面
		}

		Log.info("页面文件'", entry[0], "'被修改");
		
		return new MsgEmity(true, "保存成功", 8999);
	}
	
	/**
	 * 读取文件
	 * @param htmlFormInfos
	 * @return
	 */
	private String[] readHtml(HtmlFormInfo htmlFormInfos) {
		StringBuilder sb = new StringBuilder(System.getProperty("user.dir").replaceAll("\\\\", "/"))
			.append("/data").append(htmlFormInfos.getsPath());
		
		String filePath = sb.toString();
		String sUserId = ModuleUtil.currentLoginUserId();
		
		String saveFile = "";
		{
			int iSt = filePath.lastIndexOf("/");
			int iEd = filePath.lastIndexOf(".html");
			StringBuilder temp = new StringBuilder()
				.append(filePath.substring(0, iSt))
				.append("/temp")
				.append(filePath.substring(iSt, iEd))
				.append("_")
				.append(sUserId)
				.append(".html");
			saveFile = temp.toString();
		}
		
		File file = new File(saveFile);
		if (file.exists()) {
			filePath = saveFile;
		}

		MsgEmity me = FileUtil.readFile(filePath);
		if (!me.isSuccess()) {
			return new String[]{ saveFile, "" };
		}
		
		String html = me.getData();
		String[] result = {saveFile, html};
		
		return result;
	}
	
	/**
	 * 排序坐标
	 * @param list
	 * @return
	 */
	private List<HtmlFormControlInfo> sortPoint(List<HtmlFormControlInfo> list) {
		List<HtmlFormControlInfo> result = new ArrayList<HtmlFormControlInfo>();
		
		Collections.sort(list, new Comparator<HtmlFormControlInfo>() {
			
			@Override
			public int compare(HtmlFormControlInfo o1, HtmlFormControlInfo o2) {
				if (o1.getiTop() == o2.getiTop()) {
					return o1.getiLeft() - o2.getiLeft();
				} else {
					return o1.getiTop() - o2.getiTop();
				}
			}
		});
		
		return result;
	}

	/**
	 * 测试
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		HtmlFormInfo htmlFormInfos = new HtmlFormInfo();
		htmlFormInfos.setsName("edit_00000003.html");
		htmlFormInfos.setsPath("serviceparams/temp/edit_00000003.html");
		htmlFormInfos.setiFormWidth(540);
		htmlFormInfos.setiFormHeight(232);
		
		HtmlFormControlInfo sName = new HtmlFormControlInfo();
		sName.setsName("MysName");
		sName.setiTop(76);
		sName.setiLeft(258);
		htmlFormInfos.getHtmlFormControlInfos().add(sName);

		HtmlFormControlInfo sEnglish = new HtmlFormControlInfo();
		sEnglish.setsName("MysEnglish");
		sEnglish.setiTop(0);
		sEnglish.setiLeft(13);
		htmlFormInfos.getHtmlFormControlInfos().add(sEnglish);

		HtmlFormControlInfo sValue = new HtmlFormControlInfo();
		sValue.setsName("MysValue");
		sValue.setiTop(6);
		sValue.setiLeft(263);
		htmlFormInfos.getHtmlFormControlInfos().add(sValue);

		HtmlFormControlInfo sMD5 = new HtmlFormControlInfo();
		sMD5.setsName("MysMD5");
		sMD5.setiTop(71);
		sMD5.setiLeft(12);
		sMD5.setiColSize(7);
		htmlFormInfos.getHtmlFormControlInfos().add(sMD5);

		HtmlFormControlInfo sMemo = new HtmlFormControlInfo();
		sMemo.setsName("MysMemo");
		sMemo.setiTop(124);
		sMemo.setiLeft(0);
		sMemo.setiColSize(23);
		htmlFormInfos.getHtmlFormControlInfos().add(sMemo);
		
		HtmlDesignServiceImpl htmlDesignServiceImpl = new HtmlDesignServiceImpl();
		
		htmlDesignServiceImpl.save(htmlFormInfos);
	}
	
}
